  
package com.xebest.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xebest.common.enums.erp.order.VenOrderLogisticsEnum;
import com.xebest.common.enums.erp.order.VenOrderPayTypeEnum;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreRecordInventoryFlagEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreTypeEnum;
import com.xebest.web.mapper.read.XeVenOrderReadMapper;
import com.xebest.web.mapper.read.XeVenSendReadMapper;
import com.xebest.web.model.XeVenFinSalesBillDetailEntity;
import com.xebest.web.model.XeVenFinSalesBillEntity;
import com.xebest.web.model.XeVenOrderInfoDetailEntity;
import com.xebest.web.model.XeVenOrderInfoEntity;
import com.xebest.web.model.XeVenOrderLogistics;
import com.xebest.web.model.XeVenStoreDelivDetailEntity;
import com.xebest.web.model.XeVenStoreDeliveryEntity;
import com.xebest.web.service.XeVenFinSalesBillService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.service.XeVenSendGoodsService;
import com.xebest.web.service.XeVenStoreDelivService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.service.XeVenSummaryPurchService;
import com.xebest.web.view.XeVenSendView;

/**
 * 鲜易云ERP订单发货业务
 * @desc: xebest-erp  
 * @author: 李贝贝  
 * @createTime: 2017年6月29日 下午2:23:40  
 * @history:  
 * @version: v1.0
 */
@Service
public class XeVenSendGoodsServiceImpl implements XeVenSendGoodsService {

	 private static final Logger log = LoggerFactory.getLogger(XeVenSendGoodsServiceImpl.class);//日志记录类

	 @Autowired
	 private XeVenOrderService xeVenOrderService;//订单业务相关
	 
	 @Autowired
	 private XeVenStoreDelivService xeVenStoreDelivService;//出库信息
	 
	 @Autowired
	 private XeVenOrderReadMapper  xeVenOrderReadMapper;//订单查询业务
	 
	 @Autowired
	 private XeVenSendReadMapper xeVenSendReadMapper;//发货查询业务
	 
	 @Autowired
	 private XeVenStoreReceiptService xeVenStoreReceiptService;//入库业务
	 
	 @Autowired
	 private XeVenSummaryPurchService xeVenSummaryPurchService;//整柜仓业务
	 
	 @Autowired
	 private XeVenFinSalesBillService xeVenFinSalesBillService;//收款单业务

	 /**
	  * 订单发货
	  * @author: 李贝贝
	  * @createTime: 2017年6月29日 下午3:49:51  
	  * @history:  
	  * @param orderEntity
	  * @return
	  * @throws Exception int
	  */
	 @Transactional(value="writeTransactionManager")
	 public  int updateSend(XeVenSendView sendView) throws Exception{
		 int sendResult = 0 ;
		 String userCode = sendView.getUserCode();//商户编码
		 String orderId = sendView.getOrderId();//订单号
		 String storeId = sendView.getStoreId();//仓库标识
		 String createUser = sendView.getCreaterUser();//创建人
		 String storeName = sendView.getStoreHouseName();//仓库名称

		 //1、更新订单状态为已发货
		 Date sendTime = sendView.getSendTime();
		 XeVenOrderInfoEntity paramOrder = new XeVenOrderInfoEntity();
		 paramOrder.setUserCode(userCode);//商户编码
		 paramOrder.setOrderId(orderId);//订单号
		 paramOrder.setModfiyUser(sendView.getModfiyUser());//修改人
		 paramOrder.setOrderStatus(VenOrderStatusEnum.SEND.getValue());//订单发货状态
		 paramOrder.setOldOrderStatus(VenOrderStatusEnum.WAIT_SEND.getValue());//预更新状态
		 paramOrder.setSendTime(sendTime);
		 sendResult = xeVenOrderService.updateXeVenOrder(paramOrder);//更新已发货
		 log.info("订单发货信息：商户{},订单号{},发货人{},发货执行结果{}!",userCode,orderId,createUser,sendResult);
		 //更新发货，成功
		 if (sendResult > 0) {
			 List<XeVenOrderInfoDetailEntity> orderDetailList = sendView.getOrderDetailList();//订单明细信息
			 //2、出库   判断仓库类型  1自有仓库，2三方仓库，3零采仓库，4整柜仓库，5退货仓库
			 //如果仓库类型为零采仓库 ，则执行零采出库逻辑
			 if (VenStoreTypeEnum.ZERO_STORE.getValue() == sendView.getStoreType()) {
				 //零采仓和整柜仓的订单发货时，根据实发量对关联的采购单进行一次入库操作并将采购单置为完成状态（实发量=采购量：正常完成；实发量≠采购量：异常完成），同时按照订单实发量进行一次出库操作。
				 int result = xeVenStoreReceiptService.autoReceiptSendZeroStore(sendView);
				 log.info("订单{}发货信息：零采仓出库执行结果{}",orderId,result);
				 this.updateSummary(orderId);
			 }else if (VenStoreTypeEnum.ALLOCATE_STORE.getValue() == sendView.getStoreType()) {
				//整柜仓出库逻辑
				 int result = xeVenStoreReceiptService.autoReceiptSendAllotStore(sendView);
				 log.info("订单{}发货信息：整柜仓出库执行结果{}",orderId,result);
				 this.updateSummary(orderId);
			 }else {
				 //其它仓库  判断仓库是否开启记录库存 ：1是，2否
				 if (VenStoreRecordInventoryFlagEnum.YES.getValue() == sendView.getRecordInvFlag()) {
					 XeVenStoreDeliveryEntity delivery = new XeVenStoreDeliveryEntity();//出库单初始化
					 //拼装出库信息
					 delivery.setUserCode(userCode);//商户编码
					 delivery.setRelationOrder(orderId);//关联单号 此处为订单号
					 delivery.setStoreId(storeId);//仓库编码
					 delivery.setStoreName(storeName);//仓库名称
					 delivery.setDeliveryType(VenStoreDeliveryTypeEnum.SALES_DELIVERY.getValue());//销售出库
					 delivery.setCreateUser(createUser);//制单人
					 //拼装出库商品明细信息
					 List<XeVenStoreDelivDetailEntity> deliveryDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();//出库商品明细容器
					 XeVenStoreDelivDetailEntity deliveryDetail = null ;//初始化出库明细对象
					 for (XeVenOrderInfoDetailEntity orderDetail : orderDetailList) {
						 deliveryDetail = new XeVenStoreDelivDetailEntity();
						 deliveryDetail.setProSku(orderDetail.getProSku());//商品SKU
						 deliveryDetail.setProOutNum(orderDetail.getRealSendNum());//获取商品实发量 扣减库存使用
						 deliveryDetail.setPlanOutNum(orderDetail.getPurchaseNum());//获取商品的购买量
						 deliveryDetail.setProMainImg(orderDetail.getProPicture());//商品图片
						 deliveryDetail.setProNum(orderDetail.getProNum());//商品货号
						 deliveryDetail.setProCategoryId(orderDetail.getProOrgCode());//商品分类信息 三级（_922_119_964_）
						 deliveryDetail.setProCategoryName(orderDetail.getProOrgCodeName());//商品分类名称信息
						 deliveryDetail.setProName(orderDetail.getProName());//商品名称
						 deliveryDetail.setProSpecValue(orderDetail.getSpecValue());//规格值
						 deliveryDetail.setProSpecName(orderDetail.getSpecName());//规格名称
						 deliveryDetail.setProPricingType(orderDetail.getPricingType());//商品计价方式
						 deliveryDetail.setProUnit(orderDetail.getProUnit());//商品单位
						 deliveryDetail.setCreateUser(createUser);//出库人
						 deliveryDetailList.add(deliveryDetail);//添加出库商品明细信息
					 }
					 delivery.setDelivDtailList(deliveryDetailList);//出库明细信息
					 int deliveryResult = xeVenStoreDelivService.saveDeliv(delivery);//保存出库信息（包括库存扣减）
					 log.info("出库信息：商户{},订单号{},出库人{},出库执行结果{}!",userCode,orderId,createUser,deliveryResult);
				 }
			 }
			 //拼装收款单参数
			 XeVenFinSalesBillEntity pBill = new XeVenFinSalesBillEntity();//收款单信息
			 pBill.setUserCode(userCode);
			 pBill.setVenName(sendView.getVenName());
			 pBill.setOperMode(sendView.getVenType());
			 pBill.setOrderId(orderId);
			 pBill.setSbillStatus(1);
			 pBill.setPayAmount(sendView.getPayAmount());
			 pBill.setEpayReceAmt(sendView.getEpayReceAmt());
			 pBill.setGoodsAmount(sendView.getGoodsAmount());
			 pBill.setPayType(sendView.getPayType());
			 pBill.setOrderStatus(VenOrderStatusEnum.SEND.getValue());
			 pBill.setCaProvinceId(sendView.getCaProvinceId());
			 pBill.setCaCityId(sendView.getCaCityId());
			 pBill.setCaAreaId(sendView.getCaAreaId());
			 pBill.setCaStreet(sendView.getCaStreet());
			 pBill.setCaConsignee(sendView.getCaConsignee());
			 pBill.setOrderRemark(sendView.getOrderRemark());
			 pBill.setSendTime(sendTime);
			 pBill.setDifferAmount(sendView.getDifferAmount());
			 pBill.setCreateUser(createUser);
			 if (VenOrderPayTypeEnum.ONLINE_PAY.getValue() == sendView.getPayType()) {
				pBill.setRealSbillAmount(sendView.getEpayReceAmt());
				pBill.setSbillPayType(3);
			}
			 //拼装收款单商品明细参数
			 List<XeVenFinSalesBillDetailEntity> sbDetailList = new ArrayList<XeVenFinSalesBillDetailEntity>();
			 XeVenFinSalesBillDetailEntity sbillDetail = null;
			 for (XeVenOrderInfoDetailEntity skuDetail : orderDetailList) {
				 sbillDetail = new XeVenFinSalesBillDetailEntity();
				 sbillDetail.setProSku(skuDetail.getProSku());
				 sbillDetail.setProName(skuDetail.getProName());
				 sbillDetail.setProNum(skuDetail.getProNum());
				 sbillDetail.setSpecName(skuDetail.getSpecName());
				 sbillDetail.setSpecValue(skuDetail.getSpecValue());
				 sbillDetail.setProUnit(skuDetail.getProUnit());
				 sbillDetail.setProPrice(skuDetail.getProPrice());
				 sbillDetail.setProCostPrice(skuDetail.getProCostPrice());
				 sbillDetail.setPricingType(skuDetail.getPricingType());
				 sbillDetail.setNormWeight(skuDetail.getNormWeight());
				 sbillDetail.setPurchaseNum(skuDetail.getPurchaseNum());
				 sbillDetail.setRealSendNum(skuDetail.getRealSendNum());
				 sbillDetail.setProPayAmount(skuDetail.getProPayAmount());
				 sbillDetail.setDifferAmount(skuDetail.getDifferenceAmount());
				 sbillDetail.setFrozenFlag(skuDetail.getFrozenFlag());
				 sbDetailList.add(sbillDetail);
			 }
			 pBill.setBillDetailEntityList(sbDetailList);
			 //3、收款单创建
			 int  resultPb =  xeVenFinSalesBillService.saveFinSalesBill(pBill);
			 log.info("订单{}发货信息：收款单创建执行结果{}",orderId,resultPb);
			 
			
			 //6、插入物流信息
			 XeVenOrderLogistics logt = new XeVenOrderLogistics();
			 logt.setLogtsStatus(VenOrderLogisticsEnum.IN_TRANSIT.getValue());
			 logt.setUserCode(userCode);
			 logt.setOrderId(orderId);
			 Map<String, Object> smsMap = new HashMap<String, Object>();
			 smsMap.put("orderId", orderId);
			 Map<String, Object> carMap = xeVenSendReadMapper.getCarMsgByOrderId(smsMap);
			 if (null != carMap) {
				//预计2017.06.20 18:00送达卸货点：工区路160号双龙冷库。
				 logt.setSendCarMsg("预计"+(carMap.get("unload_time") != null ? carMap.get("unload_time").toString():"")+"送达卸货点："+(carMap.get("unload_addr") != null ? carMap.get("unload_addr").toString():""));;
			 }
			 int  result = xeVenOrderService.updateOrderLogistics(logt,null);	
			 log.info("订单{}发货信息：插入物流信息执行结果{}",orderId,result);
		 } 
		 return sendResult ;
	 }
	 
	
	
	/**
	 * 查询待发货的订单
	 * @author: 李贝贝
	 * @createTime: 2017年7月28日 下午2:14:45
	 * @history:
	 * @param map orderIds 订单号  userCode 商户编码
	 * @return List<XeVenSendView>
	 */
	public List<XeVenSendView> queryWaitSendList(Map<String, Object> map) {
		List<XeVenSendView> sendViews = xeVenSendReadMapper.queryWaitSendList(map);// 查询待发货订单
		Map<String, Object> detailMap = null;
		for (XeVenSendView xeVenSendView : sendViews) {
			detailMap = new HashMap<String, Object>();
			detailMap.put("orderId", xeVenSendView.getOrderId());//订单号
			detailMap.put("userCode", xeVenSendView.getUserCode());//商户编码
			xeVenSendView.setOrderDetailList(xeVenOrderReadMapper.getOrderDetailByParam(detailMap));// 查询订单明细信息
		}
		return sendViews;
	}
    
	/**
	 * 更新汇总采购单中间表订单状态
	 * @author: 李贝贝
	 * @createTime: 2017年8月14日 下午7:35:23  
	 * @history:  
	 * @param orderId void
	 */
	private void updateSummary(String orderId){
		 Map<String, Object> params= new HashMap<String, Object>();
		 params.put("orderId", orderId);
		 params.put("orderStatus", VenOrderStatusEnum.SEND.getValue());
		 int result = xeVenSummaryPurchService.updateXeVenSummaryPurch(params);
		 log.info("更新汇总采购单中间表订单状态,单号{}执行结果{}",orderId,result);
	}
    
	
	/**
	 * 查询客户姓名 
	 * @author: 李贝贝
	 * @createTime: 2017年9月12日 下午5:16:06  
	 * @history:  
	 * @param map
	 * @return Map<String,Object>
	 */
	public Map<String, Object> getUserName(Map<String, Object> map){
		return xeVenSendReadMapper.getUserName(map);
	}
	
	/**
	 * 查询派车信息
	 * @author: 李贝贝
	 * @createTime: 2017年9月12日 下午5:16:10  
	 * @history:  
	 * @param map
	 * @return Map<String,Object>
	 */
	public Map<String, Object> getCarMsgByOrderId(Map<String, Object> map){
		return xeVenSendReadMapper.getCarMsgByOrderId(map);
	}
}
  
